package com.platform.interceptor;

import com.platform.bean.JwtProperties;
import com.platform.exception.BadRequestException;
import com.platform.exception.TokenExpiredException;
import com.platform.utils.JwtTokenUtils;
import com.platform.utils.RedisUtils;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Key;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
//        String rememberMeToken = request.getHeader("RememberMeToken");
        // 获取请求的URI
        String requestURI = request.getRequestURI();
        System.out.println("请求uri " + requestURI);
        System.out.println("请求urL" + request.getRequestURL());
//        // 定义不需要Token验证的路径
//        List<String> exemptPaths = Arrays.asList("/auth/adminLogin", "/auth/register");
//        // 检查请求路径是否在免验证列表中
//        if (exemptPaths.stream().anyMatch(requestURI::contains)) {
//            System.out.println("登录注册请求被拦截");
//            // 如果是免验证路径请求，则跳过Token验证
//            return true; // 继续处理请求
//        }
        // TODO 针对get请求中传递username的情况，把username和token进行比较，看看是否对的上

        if (token != null && !StringUtils.isBlank(token)) {
            byte[] keyBytes = Decoders.BASE64.decode(jwtProperties.getBase64Secret());
            Key key = Keys.hmacShaKeyFor(keyBytes);
            token = token.substring(7);
            System.out.println("获取到的token：" + token);
            // 没携带token
            if (StringUtils.isBlank(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置401状态码
                response.getWriter().write("token为空");
                return false; // 阻止请求继续处理
                // throw new BadRequestException("token为空");
            }
            // 带了token但redis找不到
            if (StringUtils.isBlank((String)redisUtils.get(jwtTokenUtils.loginUserKey(token)))) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置401状态码
                response.getWriter().write("登录状态过期，请重新登录");
                return false;
                // throw new TokenExpiredException("登录状态过期，请重新登录");
            }

            // 带了token且redis也找得到
            redisUtils.updateKeyTtl(jwtTokenUtils.loginUserKey(token),jwtProperties.getTokenValidityInSeconds(), TimeUnit.MILLISECONDS);
        }
        return true;
    }
}